package com.yc.d0316;

import com.google.gson.Gson;
import com.yc.d0316.biz.BizException;
import com.yc.d0316.biz.BookBiz;
import com.yc.demo.bean.Result;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "SaveBookServlet", value = "/SaveBookServlet.s")
public class SaveBookServlet extends HttpServlet {

    private BookBiz biz = new BookBiz();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String bookname = request.getParameter("bookname");
        final String bookauthor = request.getParameter("bookauthor");
        final String bookpress = request.getParameter("bookpress");
        final String pressdate = request.getParameter("pressdate");
        final String bookimage = request.getParameter("bookimage");

        final String id = request.getParameter("id");

        Result result;
        try {
            if(id!=null){
                biz.modify(id, bookname, bookauthor,bookpress, pressdate,bookimage);
            } else {
                biz.create(bookname, bookauthor,bookpress, pressdate,bookimage);
            }
            result = new Result(1, "图书保存成功", null);
        } catch (BizException e) {
            e.printStackTrace();
            result = new Result(0, e.getMessage(), null);
        }

        final String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }
}
